/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConfigurationMenu.Java
 *
 * Created on 27.Kasm.2009, 16:04:38
 */

package com.meraklisina.latexeditor;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;

import org.w3c.dom.*;

/**
 *
 * @author Alper Selvi
 */

public class ConfigurationMenu extends javax.swing.JPanel implements KeyListener {
    private JDialog dialog;
    private String onTheFlyChoice = "";
        /** Creates new form ConfigurationMenu */
    public ConfigurationMenu(JDialog jd) {
        this.dialog=jd;
        
        this.setFocusable(true);
        this.addKeyListener(this);

        initComponents();

        TxtMiktexPath.addKeyListener(this);
        BtnCancel.addKeyListener(this);
        RBNo.addKeyListener(this);
        RBYes.addKeyListener(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BGOnTheFlyCompilation = new javax.swing.ButtonGroup();
        BtnCancel = new javax.swing.JButton();
        BtnSetMiktexPath = new javax.swing.JButton();
        BtnSaveSettings = new javax.swing.JButton();
        TxtMiktexPath = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabelLanguage = new javax.swing.JLabel();
        RBNo = new javax.swing.JRadioButton();
        RBYes = new javax.swing.JRadioButton();
        LanguageComboBox = new javax.swing.JComboBox();
        
        lang.LoadLanguage(BlueLatexEditor._language);
        
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        BtnSetMiktexPath.setText(lang.SetMiktexPath);
        BtnSetMiktexPath.setName("SetMiktexPath"); 
        BtnSetMiktexPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	BtnSetMiktexPathActionPerformed(evt);
            }
        });
        
        BtnSaveSettings.setText(lang.SaveAndExit);
        BtnSaveSettings.setName("SaveSettings"); 
        BtnSaveSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	BtnSaveSettingsMiktexPathActionPerformed(evt);
            }
        });
        
        BtnCancel.setText(lang.Cancel);
        BtnCancel.setName("BtnCancel");
        BtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelActionPerformed(evt);
            }
        });

        TxtMiktexPath.setName("TxtMiktexPath"); 

        jLabel1.setText(lang.MiktexPath);
        jLabel1.setName("jLabel1"); 
               
        jLabel3.setText(lang.EnableOnTheFlyCompilation);
        jLabel3.setName("jLabel3"); 
        
        jLabelLanguage.setText(lang.LanguageSelection);
        jLabelLanguage.setName("jLabelLanguage"); 

        BGOnTheFlyCompilation.add(RBNo);
        RBNo.setText(lang.No);
        RBNo.setName("RBNo"); 
        RBNo.setSelected(true);
        RBNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RBNoActionPerformed(evt);
            }
        });
        
        LanguageComboBox.setModel(new javax.swing.DefaultComboBoxModel(ph.FindExistingLanguageFiles()));
        LanguageComboBox.setName("jComboBoxSections");

        BGOnTheFlyCompilation.add(RBYes);
        RBYes.setText(lang.Yes);
        RBYes.setName("RBYes"); 
        RBYes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	RBYesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabelLanguage))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(RBNo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(RBYes))
                    .addComponent(TxtMiktexPath, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                    .addComponent(LanguageComboBox))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(BtnCancel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(BtnSetMiktexPath, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(BtnSaveSettings, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                	.addComponent(BtnSetMiktexPath)
                    .addComponent(TxtMiktexPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                    	.addComponent(BtnSaveSettings)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(RBYes)
                        .addComponent(RBNo)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    	.addComponent(jLabelLanguage)
                    	.addComponent(LanguageComboBox)
                        .addComponent(BtnCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        
        LoadSettings();
    }// </editor-fold>//GEN-END:initComponents

    ProjectHelpers ph = new ProjectHelpers();
    
       private void BtnSetMiktexPathActionPerformed(java.awt.event.ActionEvent evt) {
        
    	JFileChooser fileChooser = new JFileChooser ();
    	fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    	int result = fileChooser.showOpenDialog(null);
    	File fFile = null;
    	String fileToWrite = null; 
    	
    	if (result == JFileChooser.APPROVE_OPTION)
        {
    		fFile = new File(fileChooser.getSelectedFile().toString());
            fFile = fileChooser.getSelectedFile();
            fileToWrite = fFile.toString() + "\\";
        }
    	else
    	{
    		return;
    	}
    	
    	TxtMiktexPath.setText(fileToWrite);
	}

       Language lang = new Language();
       
    private void BtnCancelActionPerformed(java.awt.event.ActionEvent evt) {
        this.dialog.setVisible(false);
    }
    
    private void BtnSaveSettingsMiktexPathActionPerformed(java.awt.event.ActionEvent evt) {
 
        Document domDoc = XmlHandler.createXmlDocument() ;
        
        Element configList = domDoc.createElement("Configuration");
        
        Element configElements = domDoc.createElement("ProgramConfig") ;
        
        Element miktexPath = domDoc.createElement("MiktexPath");
        miktexPath.setTextContent(TxtMiktexPath.getText());
        configElements.appendChild(miktexPath) ;
        
        Element onTheFlyCompilation = domDoc.createElement("onTheFlyCompilation");
        onTheFlyCompilation.setTextContent(onTheFlyChoice);
        configElements.appendChild(onTheFlyCompilation);
                
        Element Language = domDoc.createElement("Language");
        Language.setTextContent(LanguageComboBox.getSelectedItem().toString());
        configElements.appendChild(Language);
        
        configList.appendChild(configElements);
        domDoc.appendChild(configList) ;
        
        String xmlString = XmlHandler.createXmlString(domDoc) ;

        try {
			FileWriter fw = new FileWriter(new File("Configuration.xml"));
			fw.write(xmlString);
			fw.flush();
			fw.close();
			
			BlueLatexEditor._miktexPath = TxtMiktexPath.getText();
			
			String CompilationChoice = onTheFlyChoice;
	    	if (CompilationChoice.equalsIgnoreCase("Yes"))
	    		BlueLatexEditor._onTheFlyCompilation = true;
	    	else
	    		BlueLatexEditor._onTheFlyCompilation = false;

	    	BlueLatexEditor._language = LanguageComboBox.getSelectedItem().toString();
	    	
	    	this.dialog.setVisible(false);
	    	
		} catch (IOException ex) {
			Logger.getLogger(AppConfigReader.class.getName()).log(Level.SEVERE,
					null, ex);
    	}
		
    }

    private void LoadSettings()
    {
    	XmlHandler ConfigurationHandler = new XmlHandler("Configuration.xml");
    	    	    	
    	NodeList config = ConfigurationHandler.GetElementsByTagName("ProgramConfig");
    	
    	int a = config.getLength();
    	if (a < 1)
    		return;
    	
    	Node Configuration = config.item(0);
    	TxtMiktexPath.setText(ConfigurationHandler.GetChildNodeValue(Configuration, "MiktexPath"));
    	String CompilationChoice = ConfigurationHandler.GetChildNodeValue(Configuration, "onTheFlyCompilation");
    	
    	if(CompilationChoice != null)
    	{
    		if (CompilationChoice.equalsIgnoreCase("Yes"))
    			RBYes.setSelected(true);
        	else
        		RBNo.setSelected(true);    		
    	}
    	else
    	{
    		RBNo.setSelected(true);
    	}
    	
    	String LanguageChoice = ConfigurationHandler.GetChildNodeValue(Configuration, "Language");
    	if (LanguageChoice != null)
    		LanguageComboBox.setSelectedItem(LanguageChoice);
    	else
    		LanguageComboBox.setSelectedItem("English");
    	
    }
    
	private void RBNoActionPerformed(java.awt.event.ActionEvent evt) {
		onTheFlyChoice = "No";
	}
	
	private void RBYesActionPerformed(java.awt.event.ActionEvent evt) {
		onTheFlyChoice = "Yes";
	}
	
	public void keyPressed(java.awt.event.KeyEvent evt)
	{
	        if(evt.getKeyCode()==KeyEvent.VK_ESCAPE)
	            this.dialog.setVisible(false);
	}
	public void keyTyped(java.awt.event.KeyEvent ke){}
	public void keyReleased(java.awt.event.KeyEvent ke){}
    
    private void formKeyPressed(java.awt.event.KeyEvent evt) {
     
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup BGOnTheFlyCompilation;
    private javax.swing.JButton BtnCancel;
    private javax.swing.JButton BtnSetMiktexPath;
    private javax.swing.JButton BtnSaveSettings;
    private javax.swing.JRadioButton RBYes;
    private javax.swing.JRadioButton RBNo;
    private javax.swing.JTextField TxtMiktexPath;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelLanguage;
    private javax.swing.JComboBox LanguageComboBox;
    // End of variables declaration//GEN-END:variables

}
